package com.dreams.dream.common.async.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SingleThreadedClaimStrategy;
import com.lmax.disruptor.YieldingWaitStrategy;

public class EventResultHandlerImp implements EventResultHandler {

    // MILLISECONDS default is one seconds
    protected int timeoutforeturnResult = 10000;

    protected ValueEventProcessor valueEventProcessor;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public EventResultHandlerImp() {
        super();
        RingBuffer ringBuffer = new RingBuffer<EventResultDisruptor>(new EventResultFactory(), new SingleThreadedClaimStrategy(8), new YieldingWaitStrategy());
        this.valueEventProcessor = new ValueEventProcessor(ringBuffer);

    }

    /**
     * send event result
     * 
     */
    public void send(Object result) {
        valueEventProcessor.send(result);
    }

    public Object get() {
        Object result = null;
        EventResultDisruptor ve = valueEventProcessor.waitFor(timeoutforeturnResult);
        if (ve != null) {
            result = ve.getValue();
            ve.clear();
            clear();
        }
        return result;

    }

    public Object getBlockedValue() {
        Object result = null;
        EventResultDisruptor ve = valueEventProcessor.waitForBlocking(timeoutforeturnResult * 100);
        if (ve != null) {
            result = ve.getValue();
            ve.clear();
            clear();
        }
        return result;
    }

    public void clear() {
        valueEventProcessor.clear();
    }

    public int getTimeoutforeturnResult() {
        return timeoutforeturnResult;
    }

    public void setWaitforTimeout(int timeoutforeturnResult) {
        this.timeoutforeturnResult = timeoutforeturnResult;
    }

}
